<template>
  <div style="height: 100%">
  <ul class="infinite-list"  style="overflow:auto" v-loading="loading">
    <li v-for="item in this.note" v-on:click="getnote($event,item.noteId,item)"
        :class="{'infinite-list-item':true,'briefH':$store.state.user.briefH}"
        @contextmenu.stop.prevent="$refs.newestMenu.showMenu($event,item);getnote($event,item.noteId,item)" >
      <div class="content">
        <img :src="item.url" class="typeIcon" alt=""><h5 id="title" v-model="noteinfo.title">{{item.noteTitle}}</h5>
        <li class="el-icon-top" v-show="item.z!=0" style="color: red;font-size: 26px;float: right"></li>
        <ul class="tool-bar">
          <li :class="{'iconfont icon-xing':!item.star,'iconfont icon-xing stared':item.star}" @click="addstar(item)"></li>
          <li class="iconfontnew icon-fenxiang"></li>
          <li class="iconfont icon-huishouzhan" @click="notedelete(item.noteId)"></li>
        </ul>
        <p :class="{'above':true,'briefP':$store.state.user.briefP}">{{item.content}}</p>
        <span id="date" v-model="noteinfo.date">{{item.createTime}}</span>
      </div>
    </li>
  </ul>
  <e-vue-contextmenu ref="newestMenu"
                     class="widget-menu"
                     @ctx-show="showmenu">
    <li class="widget-menu-item" @click="addstar(currentRightClick);hidemenu()"><span>{{star}}</span></li>
    <li class="widget-menu-item" @click="stick(currentRightClick)"><span>{{Stick}}</span></li>
    <li class="widget-menu-item"><span>重命名</span></li>
    <li class="widget-menu-item"><span>移动到</span></li>
    <li class="widget-menu-item"><span>复制Ctrl+C</span></li>
    <li class="widget-menu-item" @click="notedelete(currentRightClick.noteId);hidemenu()"><span>删除</span></li>
    <li class="widget-menu-item"><span>下载</span></li>
    <li class="widget-menu-item" @click="pull(currentRightClick)"><span>{{wordOrPdf}}</span></li>
    <li class="widget-menu-item split-line"></li>
    <li class="widget-menu-item"><span>分享</span></li>
    <li class="widget-menu-item"><span>发送到云协作</span></li>
    <li class="widget-menu-item"><span>复制引用链接</span></li>
    <li class="widget-menu-item split-line"></li>
    <li class="widget-menu-item"><span>阅读密码</span></li>
    <li class="widget-menu-item"><span>查看历史版本</span></li>
  </e-vue-contextmenu>
  </div>
</template>

<script>
  import bus from '../../../assets/bus'
  import commonFile from '../../../assets/commonFile.png'
  import folder from '../../../assets/folder.png'
  import markdown from '../../../assets/markdown.png'
  import marked from 'marked'
    export default {
        name: "newest",
      data(){
          return{
              loading:false,
              Stick:"置顶",
              wordOrPdf:'导出为Word',
              star:'加星',
              currentRightClick:{},
              editor: {
                  info: "",
              },
              note:[],
              noteinfo:{
                title:"",
                detail:"",
                date:"",
                  noteId:Number,
                  type:Number,
              },
              abstract:true
          }
      },
        methods:{
          getnote(e,noteId,item){
              var _this=this;
              var noteinfo=_this.noteinfo;
              _this.$axios.get('/note/query',{
                  params:{noteId:noteId}
              }).then(function (res,e) {
                  console.log(res);
                  _this.noteinfo.detail=res.data.data.data;//将笔记内容放入noteinfo,不能用item.content,此时item.content已经被处理
                  _this.noteinfo.title=item.noteTitle;//获取标题dom中的内容
                  _this.noteinfo.date=item.createTime;//获取日期dom中的内容
                  _this.noteinfo.noteId=item.noteId;
                  _this.noteinfo.type=item.type;
                  _this.$emit("getnote",noteinfo)//将noteinfo传至cloudnote
              }).catch(function (err) {
                  console.log(err);
              })
                // 获取梗概dom中的内容
               // noteinfo.detail=e.currentTarget.firstElementChild.lastElementChild.previousElementSibling.textContent;
              //这里进行了一次dom排他操作，但是当数据量过大时并不适用
             var list=e.currentTarget.parentElement.children//获取列表元素放入一个集合
              for(var i=0;i<list.length;i++){
                  list[i].style.background="#FFFFFF";//遍历每个元素将其背景元素设为白色
              }
              e.currentTarget.style.background="#eaf0fb";//将目前选中的元素背景设为选中色
          },
            addstar(item){
              var _this=this;
                if (item.star==0){//若未加星，则让其加星
                    _this.$axios.post('/star/addStar',{
                        starNote:item.noteId
                    }).then(function (res) {
                        console.log(res);
                        _this.getnotelist()
                        if(res.data.code==200){
                            item.star=1;
                        }
                    }).catch(function (err) {
                        console.log(err);
                    })}else if(item.star==1){//若已加星，则取消其加星
                    _this.$axios.delete('star/cancelStar',{
                        data:{
                            starId:item.starId
                        }
                    }).then(function (res) {
                        if(res.data.code==200){
                            item.star=0;
                        }
                        console.log(res);
                    }).catch(function (err) {
                        console.log(err);
                    })

                }
            },
            getnotelist(){
              var _this=this;
                this.$axios.get('/note/queryNewest',{
                }).then(function (res) {
                    console.log(res);
                    _this.loading=false;
                       var list=res.data.data.data;
                        for(var i=0;i<list.length;i++){
                            if(list[i]==null){//去除list中的空值
                                list.splice(i,1);
                                i--;
                            }else{
                                if(list[i].folder==1){//若为文件夹
                                    list[i].url=folder;//附上文件夹图标
                                }else if(list[i].type===1){
                                    list[i].content=_this.removeTag(marked(list[i].content||'', { sanitize: true}));
                                    list[i].url=markdown;//附上md图标
                                }else{
                                    list[i].content=_this.removeTag(list[i].content);//去除html
                                    list[i].url=commonFile;//附上普通文件图标
                                }
                                list[i].createTime = _this.timestampToTime(list[i].createTime);//时间戳转换
                            }
                        }
                    _this.note=list;
                    }
                ).catch(function (err) {
                    console.log(err);
                });
            },
           timestampToTime(timestamp) {
             var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
              var Y = date.getFullYear() + '-';
              var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
             var D = (date.getDate()<10?'0'+(date.getDate()):date.getDate());
            return Y + M + D;
  },
            notedelete(noteId){
                     var _this=this;
                     this.$axios.delete('/note/delete',{
                         data:{
                             noteId:noteId
                         }
                     }).then(function (res) {
                         console.log(res);
                        if (res.data.code==200){
                            _this.getnotelist();
                        }
                     }).catch(function (err) {
                         console.log(err);
                     })
            },
            removeTag(str,len){

                if(str!=undefined)
                {   var styleregex=/<style[^>]*?>[\s\S]*?<\/style>/g;//去除style标签及其中内容
                    var str1=str.replace(styleregex,"");
                    var htmlregex=/<\/?.+?>/g//去除html标签及其中内容
                    return str1.replace(htmlregex,"");}
                else{
                    return str;
                }
            },
            showmenu(item){
                this.currentRightClick=item;
                console.log(this.currentRightClick);
                if(item.star==1){
                    this.star='取消加星'
                }else if(item.star==0){
                    this.star='加星'
                }
                if(item.type==1){
                    this.wordOrPdf="导出为PDF";
                }else if(item.type==0){
                    this.wordOrPdf="导出为Word";
                }
                if(item.z!=0){
                    this.Stick="取消置顶"
                }else{
                    this.Stick="置顶"
                }
            },
            hidemenu(){
              this.$refs.newestMenu.hideMenu();
            },
            pull(val){
                 var title=val.noteTitle
                if(val.type==0){//普通笔记，导出为word
                    this.$axios.get('/note/export/word/'+val.noteId,{
                        responseType: 'arraybuffer'
                    }).then(function (res) {
                        console.log(res);
                        if(res.status==200){
                        let blob = new Blob([res.data], {
                            type: 'application/msword'//word文档为msword,pdf文档为pdf，msexcel 为excel
                        });
                            let objectUrl = URL.createObjectURL(blob);
                        let link = document.createElement("a");
                        let fname =title; //下载文件的名字+后缀名
                        link.href = objectUrl;
                        link.setAttribute("download", fname);
                        document.body.appendChild(link);
                        link.click();
                    } else {
                        this.$message({
                            type: "error",
                            message: "导出失败"
                        })

                    }
                    }).catch(function (err) {
                        console.log(err);
                    })
                }
                else if(val.type==1){//md笔记，导出为pdf
                    this.getPdf(val.noteTitle)
                }
            },
            stick(val){
             var _this=this;
             if(val.z==0){//如果没置顶则只等
             this.$axios.put("/note/stick",{
                     noteId:val.noteId
             }).then(function (res) {
                 if(res.data.code==200){
                     _this.getnotelist();
                     _this.hidemenu();
                 }
             }).catch(function (err) {
                 console.log(err);
             })}
             else{//如果置顶了就取消置顶
                 this.$axios.delete('/note/stick',{
                     data:{
                         noteId:val.noteId
                     }
                 }).then(function (res) {
                     if(res.data.code==200){
                         _this.getnotelist();
                         _this.hidemenu();
                     }
                 }).catch(function (err) {
                     console.log(err);
                 })
             }
            },
            toHtml(val){
                var _this=this;
                let html = _this.noteinfo.detail;
                let html_ = new Blob([html],{ "type" : "text/html;charset=utf-8" })
                let formdata = new FormData();
                formdata.append('file', html_, `sdf.html`);
                console.log(html_);
                var downloadElement = document.createElement('a');
                var href = window.URL.createObjectURL(html_); //创建下载的链接
                downloadElement.href = href;
                downloadElement.download ='s.html'; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                // axios({
                //     method: 'post',
                //     url: url,
                //     data:formdata,
                //     responseType:'blob',
                // })
            }
        },
        mounted() {
            var _this=this;
            //接收从wangeditor组件传输来的组件
            // bus.$on('getinfo',(e)=>{
            //     this.editor.info=e;
            // });
            this.loading=true;
            this.getnotelist();
            this.$parent.$refs.doctree.refresh()
            this.$parent.tomydoc={
                    background: 'transparent',
                    color:'#393939',
            }
        }
    }
</script>

<style scoped>
  ::-webkit-scrollbar {display:none}
  .infinite-list{
    width: 100%;
    height: 100%;
    overflow-y: auto;
    display: block;
  }
  .infinite-list-item{
    display: inline-block;
    height: 125px;
    width: 100%;
    border-bottom: 1px solid rgba(0,0,0,0.06);
  }
  .infinite-list-item h5{
    float: left;
    display: inline-block;
    width: 34%;
    font-size: 15px;
    height: 23px;
    text-align: left;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis !important;
  }
  /*深度选择器*/
  .infinite-list-item p{
    overflow:hidden;
    /*超出范围用省略号表示*/
    text-overflow:ellipsis !important;
    font-size: 14px;
    line-height: 25px;
    width: 100%;
    height: 50px;
    text-align: left;
    display:-webkit-box;
    -webkit-box-orient:vertical;
    /*显示行数为2*/
    -webkit-line-clamp:2;
    /*自动换行*/
    word-wrap: break-word;
    word-break: break-all;

  }
  .infinite-list-item .content #date{
    height: 15px;
    width: 35%;
    position: absolute;
    left: 20px;
    bottom: 8px;
    display:inline-block;
    color: rgb(194,194,194);
    text-align: left;
  }
  .infinite-list-item .content{
    height: 100%;
    width: 100%;
    padding: 15px 20px;
    box-sizing: border-box;
    position: relative;
  }
  .infinite-list li :hover{
    background: #eaf0fb !important;
  }

  .infinite-list li :hover .tool-bar{
    visibility: visible;
    cursor: pointer;
  }
  .tool-bar{
    /*width: 50px;*/
    /*height: 15px;*/
    /*display: none;*/
    float: right;
    display: inline-block;
    visibility:hidden;
  }
  .tool-bar li{
    float: left;
    margin-right: 10px;
    font-size: 20px;
    position: relative;
  }
  .stared{
    color: #ffcb33;
  }
  .briefP{
    display: none !important;
  }
  .briefH{
    height: 75px;
  }
  .widget-menu{
    display: inline-block;
    width: 125px ;
    background: #ffffff;
    z-index: 1000;
    position: absolute;
    left: 25px;
    top: 50px;
    box-shadow: 0px 1px 16px 0 rgba(90, 109, 122, 0.41);
    padding: 0;
    border-radius: 0;
  }
  .widget-menu .widget-menu-item{
    display: inline-block;
    float: left;
    width: 100%;
    cursor: pointer;
    height: 30px;
    color: #999;
    font-size: 12px;

  }
  .widget-menu .widget-menu-item span{
    display: inline-block;
    float: left;
    position: relative;
    top: 25%;
    margin-left: 20px;
    /*覆写行高以避免继承父元素行高*/
    line-height: 100%;
  }
  .widget-menu .widget-menu-item:hover{
    background: #ebf3fd;
    color: #7ab2f3;
  }
  .split-line{
    height: 0 !important;
    border-bottom:#ebf3fd solid 1px;
  }
  .typeIcon{
    display: inline-block;
    float: left;
    height: 22px;
    /*margin-top: 1px;*/
    width: 22px;
    background: red;
    margin-right: 15px;
  }
</style>
